package com.letoo.sso.dataaccess.dao.cahce.impl;

import java.util.List;

import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Repository;

import com.letoo.sso.dataaccess.dao.cahce.AppBaseConfigCacheDAO;
import com.letoo.sso.dataaccess.domain.dbo.AppBaseConfigDO;

@Repository("appBaseConfigCacheDAO")
public class AppBaseConfigCacheDAOImpl extends BaseCacheDAOImpl implements AppBaseConfigCacheDAO {
    public static String PREFIX_REGISTER_CONFIG = "appbaseconfig:";

    // 有效期30分钟
    // private static long CAPTCHA_EXPIRE_TIME = 30 * 60;

    @Override
    public String getAppBaseConfig(final int appId, final String configKey) {
        String result = getRedisTemplate().execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) {
                byte[] key = serialize(PREFIX_REGISTER_CONFIG + appId);
                byte[] filed = serialize(configKey);
                byte[] resByte = connection.hGet(key, filed);

                return deserialize(String.class, resByte);
            }
        });

        return result;
    }

    @Override
    public boolean setAppBaseConfig(final int appId, final List<AppBaseConfigDO> appBaseConfigDOs) {
        boolean result = getRedisTemplate().execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) {
                byte[] key = serialize(PREFIX_REGISTER_CONFIG + appId);

                // 存储在Hash集合中
                for (AppBaseConfigDO appBaseConfigDO : appBaseConfigDOs) {
                    byte[] filed = serialize(appBaseConfigDO.getConfigKey());
                    byte[] value = serialize(appBaseConfigDO.getConfigValue());
                    connection.hSet(key, filed, value);
                }

                return true;
            }
        });

        return result;
    }

}
